package network.server.handler.BankHandler;

import module.bank.BankTransactionService;
import module.bank.impl.BankTransactionServiceImpl;
import common.model.Entity.bankEntity.Transaction;
import network.protocol.Request;
import network.protocol.Response;
import network.server.RequestHandler;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;

public class BankTransactionHandler implements RequestHandler {
    private final BankTransactionService bankTransactionService;

    public BankTransactionHandler() {
        this.bankTransactionService = BankTransactionServiceImpl.getInstance();
    }

    @Override
    public Response<?> handle(Request req) {
        Map<String, Object> params = req.getParams();
        String action = req.getAction();
        action = action.substring(action.indexOf('.') + 1);

        if (params == null) {
            return Response.error("请求参数不能为空");
        }

        try {
            switch (action) {
                case "getTransactions":
                    return handleGetTransactions(params);
                case "getAccountTransactions":
                    return handleGetAccountTransactions(params);
                case "createTransaction":
                    return handleCreateTransaction(params);
                default:
                    return Response.error("未知操作: " + action);
            }
        } catch (Exception e) {
            return Response.error("处理请求时发生错误: " + e.getMessage());
        }
    }

    // 获取交易记录（可筛选类型）
    private Response<?> handleGetTransactions(Map<String, Object> params) {
        if (!params.containsKey("accountId")) {
            return Response.error("缺少必要参数: accountId");
        }
        if (!params.containsKey("sessionId") || params.get("sessionId") == null) {
            return Response.error("缺少必要参数: sessionId");
        }

        try {
            long accountId = Long.parseLong(params.get("accountId").toString());
            String sessionId = params.get("sessionId").toString(); // 安全获取
            LocalDateTime startTime = params.containsKey("startTime") && params.get("startTime") != null
                    ? LocalDateTime.parse(params.get("startTime").toString()) : null;
            LocalDateTime endTime = params.containsKey("endTime") && params.get("endTime") != null
                    ? LocalDateTime.parse(params.get("endTime").toString()) : null;
            Integer transactionType = params.containsKey("transactionType") && params.get("transactionType") != null
                    ? Integer.parseInt(params.get("transactionType").toString()) : null;

            // TODO: 根据 sessionId 验证用户权限
            return bankTransactionService.getTransactions(accountId, startTime, endTime, transactionType);
        } catch (NumberFormatException e) {
            return Response.error("参数格式错误: accountId必须为数字");
        } catch (Exception e) {
            return Response.error("获取交易记录失败: " + e.getMessage());
        }
    }

    // 获取账户所有交易记录（不筛选类型）
    private Response<?> handleGetAccountTransactions(Map<String, Object> params) {
        if (!params.containsKey("accountId")) {
            return Response.error("缺少必要参数: accountId");
        }
        if (!params.containsKey("sessionId") || params.get("sessionId") == null) {
            return Response.error("缺少必要参数: sessionId");
        }

        try {
            long accountId = Long.parseLong(params.get("accountId").toString());
            String sessionId = params.get("sessionId").toString();
            LocalDateTime startTime = params.containsKey("startTime") && params.get("startTime") != null
                    ? LocalDateTime.parse(params.get("startTime").toString()) : null;
            LocalDateTime endTime = params.containsKey("endTime") && params.get("endTime") != null
                    ? LocalDateTime.parse(params.get("endTime").toString()) : null;

            // TODO: 根据 sessionId 验证用户权限
            return bankTransactionService.getAccountTransactions(accountId, startTime, endTime);
        } catch (NumberFormatException e) {
            return Response.error("参数格式错误: accountId必须为数字");
        } catch (Exception e) {
            return Response.error("获取账户交易记录失败: " + e.getMessage());
        }
    }

    // 创建交易记录
    private Response<?> handleCreateTransaction(Map<String, Object> params) {
        try {
            Transaction transaction = new Transaction();

            if (!params.containsKey("accountId") || params.get("accountId") == null) {
                return Response.error("缺少必要参数: accountId");
            }
            if (!params.containsKey("amount") || params.get("amount") == null) {
                return Response.error("缺少必要参数: amount");
            }
            if (!params.containsKey("transactionType") || params.get("transactionType") == null) {
                return Response.error("缺少必要参数: transactionType");
            }

            transaction.setAccountId(Long.parseLong(params.get("accountId").toString()));
            transaction.setAmount(new BigDecimal(params.get("amount").toString()));
            transaction.setTransactionType(Integer.parseInt(params.get("transactionType").toString()));

            if (params.containsKey("userId") && params.get("userId") != null) {
                transaction.setUserId(Long.parseLong(params.get("userId").toString()));
            }
            if (params.containsKey("description") && params.get("description") != null) {
                transaction.setDescription(params.get("description").toString());
            }
            if (params.containsKey("status") && params.get("status") != null) {
                transaction.setStatus(Integer.parseInt(params.get("status").toString()));
            } else {
                transaction.setStatus(1);
            }

            transaction.setCreatedAt(LocalDateTime.now());
            return bankTransactionService.createTransaction(transaction);
        } catch (NumberFormatException e) {
            return Response.error("参数格式错误: 数字类型参数必须为有效数字");
        } catch (Exception e) {
            return Response.error("创建交易记录失败: " + e.getMessage());
        }
    }
}
